<template>
  <div>
    <!-- 头部区域开始 -->
    <div style="position: fixed; top: 0; left: 0; right: 0;
                height: 120px; width: 100vw; background-color: #2c82ff; z-index: 1000;">
      <div style="display: flex;justify-content: space-between;align-items: center;">
        <div style="width: 240px;display: flex;align-items: center;">
          <span style="padding-left: 15px;font-size: 20px;font-weight: bold;color: #fff;">ExpressEasy</span>
        </div>
        <div style="display: flex;align-items: center;padding: 10px" @click="router.push('/mobilePerson')">
          <img v-if="data.user?.avatar" style="width: 50px; height: 50px;border-radius: 50%" :src="data.user?.avatar" alt="">
          <img v-else style="width: 50px; height: 50px;border-radius: 50%" src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png" alt="">
        </div>
      </div>
      <div style="width: 100%; display: flex; justify-content: space-around;">
        <div style="color: white; display: flex; flex-direction: column; align-items: center;" @click="showSignDialog">
          <el-icon size="20"><Box /></el-icon>
          取包裹
        </div>
        <div style="color: white; display: flex; flex-direction: column; align-items: center;" @click="handleAdd">
          <el-icon size="20"><Position /></el-icon>
          寄包裹
        </div>
      </div>
    </div>
    <!-- 头部区域结束 -->

    <!-- 内容区域开始 -->
    <div class="content-wrapper">
      <div style="margin-top: 120px; margin-bottom: 50px;
                  min-height: calc(100vh - 120px - 55px);  background-color: #e1e5ef;
                  display: flex; justify-content: center;overflow: auto">
        <!--   菜单区域   -->
        <div class="card" style="width: 96vw; margin: 10px">
          <el-menu
              router
              :default-active="$route.path"
              class="nav-menu"
              mode="horizontal"
              @select="handleSelect"
          >
            <el-menu-item index="/mobileHome/check">查收</el-menu-item>
            <el-menu-item index="/mobileHome/send">寄退</el-menu-item>
          </el-menu>
          <div>
            <RouterView />
          </div>
        </div>
      </div>
    </div>
    <!-- 内容区域结束 -->

    <!-- 底部区域开始 -->
    <div style=" position: fixed; bottom: 0; left: 0; right: 0;
                 height: 55px; background-color: #2c82ff; z-index: 1000;">
      <div style="height: 100%; display: flex; justify-content: space-around; align-items: center;">
        <div style="color: #ffd04b; display: flex; flex-direction: column; align-items: center;">
          <el-icon size="25"><HomeFilled /></el-icon>
          首页
        </div>
        <div style="color: white; display: flex; flex-direction: column; align-items: center;" @click="router.push('/mobilePerson')">
          <el-icon size="25"><UserFilled /></el-icon>
          个人中心
        </div>
      </div>
    </div>
    <!-- 底部区域结束 -->

    <!-- 弹窗 -->
    <el-dialog v-model="data.signDialogVisible" title="可签收包裹" width="90%">
      <el-table
          :data="data.signPackageList"
          @selection-change="handleSignSelectionChange"      style="width: 100%"
          height="400"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="packageName" label="包裹名称" />
        <el-table-column prop="pickupCode" label="取件码" />
      </el-table>

      <template #footer>
        <el-button @click="data.signDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmSign">确认签收</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="data.FormVisible" title="寄件流程" width="380" style="--el-dialog-margin-top:5vh" destroy-on-close>
      <!-- 步骤条 -->
      <el-steps :active="data.activeStep" align-center style="margin-bottom: 20px">
        <el-step title="包裹信息"></el-step>
        <el-step title="收件人"></el-step>
        <el-step title="物流选择"></el-step>
      </el-steps>

      <!-- 步骤1：包裹信息 -->
      <el-form v-show="data.activeStep === 0" ref="fromRef" :model="data.form" :rules="data.rules" label-width="80px">
        <el-form-item prop="thumbnail" label="缩略图">
          <el-upload
              action="http://localhost:8080/files/upload"
              :headers="{ token: data.user.token }"
              :on-success="handleFileSuccess"
              list-type="picture">
            <el-button type="primary">上传图片</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item prop="trackingNumber" label="单号">
          <el-input v-model="data.form.trackingNumber" placeholder="10位快递单号"/>
        </el-form-item>
        <el-form-item prop="packageName" label="包裹名称">
          <el-input v-model="data.form.packageName" placeholder="请输入名称"/>
        </el-form-item>
      </el-form>

      <!-- 步骤2：收件人 -->
      <el-form v-show="data.activeStep === 1" ref="fromRef" :model="data.form" :rules="data.rules" label-width="80px">
        <el-form-item prop="recipientName" label="姓名">
          <el-input v-model="data.form.recipientName" placeholder="收件人姓名"/>
        </el-form-item>
        <el-form-item prop="recipientPhone" label="电话">
          <el-input v-model="data.form.recipientPhone" placeholder="联系电话"/>
        </el-form-item>
        <el-form-item prop="recipientAddress" label="地址">
          <el-input v-model="data.form.recipientAddress" placeholder="详细地址"/>
        </el-form-item>
      </el-form>

      <!-- 步骤3：物流信息 -->
      <el-form v-show="data.activeStep === 2" ref="fromRef" :model="data.form" :rules="data.rules" label-width="80px">
        <el-form-item prop="courier" label="快递公司">
          <el-select v-model="data.form.courier" placeholder="请选择">
            <!-- 原有快递公司选项 -->
          </el-select>
        </el-form-item>
        <el-form-item prop="shippingTime" label="发货时间">
          <el-date-picker
              v-model="data.form.shippingTime"
              type="date"
              placeholder="选择日期"
              value-format="YYYY-MM-DD"/>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="data.form.packageIntroduction" placeholder="补充说明"/>
        </el-form-item>
      </el-form>

      <template #footer>
        <div style="display: flex; justify-content: space-between">
          <el-button
              v-if="data.activeStep > 0"
              @click="data.activeStep--">
            上一步
          </el-button>
          <div v-else></div>

          <el-button
              type="primary"
              @click="handleStepAction">
            {{ data.activeStep === 2 ? '确认提交' : '下一步' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import  {reactive, ref} from 'vue'
import {useRouter} from "vue-router";
import {ElMessage} from 'element-plus'
import request from "@/utils/request.js";

const router = useRouter()

const data = reactive({
  user: JSON.parse(localStorage.getItem('code_user') || "{}"),
  signDialogVisible: false, // 确保已定义
  signPackageList: [],
  FormVisible: false,
  form: {},
  rules: {
      trackingNumber: [
          { required: true, message: '请输入快递单号', trigger: 'blur' },
          { min: 10, max: 10, message: '快递单号长度为10位', trigger: 'blur' }
      ],
      packageName: [
          { required: true, message: '请输入包裹名称', trigger: 'blur' },
      ],
      senderName: [
          { required: true, message: '请输入寄件人姓名', trigger: 'blur' },
      ],
      senderPhone: [
          { required: true, message: '请输入寄件人电话', trigger: 'blur' },
      ],
      senderAddress: [
          { required: true, message: '请输入寄件人地址', trigger: 'blur' },
      ],
      recipientName: [
          { required: true, message: '请输入收件人姓名', trigger: 'blur' },
      ],
      recipientPhone: [
          { required: true, message: '请输入收件人电话', trigger: 'blur' },
      ],
      recipientAddress: [
          { required: true, message: '请输入收件人地址', trigger: 'blur' },
      ],
      courier: [
          { required: true, message: '请选择快递公司', trigger: 'change' }
      ],
      shippingTime: [
          { required: true, message: '请选择发货日期', trigger: 'change' }
      ]
  },
  ids: [],
  activeStep: 0,
})

const fromRef = ref();

const handleSelect = (index) => {
  router.push(index)
}

// 显示签收弹窗
const showSignDialog = async () => {
  if (!data.user?.name) {
    ElMessage.error('请先登录')
    return router.push('/login')
  }
  try {
    const res = await request.get('/package/selectPage', {
      params: {
        recipientName: data.user.name,
        state: '待签收',
        pageSize: 1000
      }
    })
    data.signPackageList = res.data?.list || []
    data.signDialogVisible = true
  } catch (error) {
    ElMessage.error('无签收包裹')
  }
}

// 处理选中
const handleSignSelectionChange = (selection) => {
  data.ids = selection.map(item => item.id)
}

// 确认签收
const confirmSign = async () => {
  if (data.ids.length === 0) {
    ElMessage.warning('请选择要签收的包裹')
    return
  }

  try {
    await request.put('/package/updateBatchStatus', {
      ids: data.ids,
      state: '已签收'
    })
    ElMessage.success('签收成功')
    data.signDialogVisible = false

    // 刷新相关页面
    if (window.currentView && window.currentView.load) {
      window.currentView.load()
    }
  } catch (error) {
    ElMessage.error('签收失败')
  }
}

// 寄包裹
const handleStepAction = async () => {
  // 验证当前步骤必填项
  const stepRules = {
    0: ['thumbnail', 'trackingNumber', 'packageName'],
    1: ['recipientName', 'recipientPhone', 'recipientAddress'],
    2: ['courier', 'shippingTime']
  }[data.activeStep]

  try {
    // 使用validate替代validateField
    const valid = await fromRef.value.validate()
    if (valid) {
      if (data.activeStep === 2) {
        add()
      } else {
        data.activeStep++
      }
    }
  } catch (error) {
    ElMessage.warning('请填写完整信息')
  }
}

const handleAdd = () => {
  data.FormVisible = true;
  data.form = {
    shippingTime: new Date().toISOString().split('T')[0],
    senderName: data.user.name,
    senderPhone: data.user.phone,
    senderAddress: data.user.address,
    state: '未发货'
  };
};

const handleFileSuccess = (res) => {
  data.form.thumbnail = res.data
}

const add = () => {
  fromRef.value.validate((valid) => {
    if (valid) {
      request.post('/package/add', data.form).then(res => {
        if (res.code === '200') {
          data.FormVisible = false;
          ElMessage.success('新增成功');
          load();
        } else {
          ElMessage.error(res.msg);
        }
      });
    }
  });
};

</script>

<style scoped>

.content-wrapper {
  margin-top: 120px;
  margin-bottom: 55px;
  min-height: calc(100vh - 120px - 55px);
  background: transparent; /* 改为透明背景 */
  position: relative;
  z-index: 1;
}

/* 创建固定定位的伪元素作为背景层 */
.content-wrapper::before {
  content: '';
  position: fixed;
  top: 120px; /* 与头部高度一致 */
  left: 0;
  right: 0;
  bottom: 55px; /* 与底部高度一致 */
  background: #e1e5ef; /* 原背景色 */
  z-index: -1; /* 置于内容下方 */
}

/* 步骤条优化 */
.el-steps {
  padding: 0 10px;
}

/* 表单区域高度统一 */
.el-dialog__body {
  min-height: 300px;
}

/* 按钮间距调整 */
.el-dialog__footer .el-button {
  margin: 0 5px;
  min-width: 80px;
}

/* 移动端表格适配 */
@media (max-width: 768px) {
  /* 紧凑型表格 */
  .el-table {
    --el-table-header-bg-color: #f5f7fa;
    --el-table-row-hover-bg-color: #f5f7fa;
  }


  /* 隐藏非必要列 */
  .el-table__header-wrapper .el-table-column--selection,
  .el-table-column--recipientPhone,
  .el-table-column--recipientAddress,
  .el-table-column--courier {
    display: none;
  }

  /* 固定重要列宽度 */
  .el-table-column--trackingNumber {
    width: 100px;
    min-width: 100px;
  }

  .el-table-column--packageName {
    width: 80px;
    min-width: 80px;
  }

  .el-input {
    transition: all 0.3s ease;
  }

  .el-button {
    transition: transform 0.1s;
  }

  .el-button:active {
    transform: scale(0.98);
  }

  /* 添加响应式提示 */
  .el-table::before {
    content: "← 左右滑动查看完整内容 →";
    display: block;
    text-align: center;
    color: #909399;
    font-size: 12px;
    padding: 4px 0;
    background: #f8f8f9;
  }
}

/* 弹窗优化 */
.el-dialog {
  border-radius: 8px;
  overflow: hidden;
}

.el-dialog__body {
  padding: 10px 15px !important;
}

/* 按钮组适配 */
.el-dialog__footer {
  display: flex;
  justify-content: space-between;
  padding: 10px 15px !important;
}

.el-dialog__footer .el-button {
  flex: 1;
  margin: 0 5px;
}
</style>
